package com.mcptt.http.operator;

import com.cloudptt.api.product.log.Log;
import com.mcptt.http.operator.file.OnUploadListener;
import com.mcptt.http.operator.file.ProgressRequestBody;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils implements Callback{
	private static final String THIS_FILE = "OkHttpUtils";
	private static OkHttpUtils okHttpUtils = null;

	public static OkHttpUtils getInstance() {
		if (okHttpUtils == null) {
			synchronized (OkHttpUtils.class) {
				if (okHttpUtils == null) {
					okHttpUtils = new OkHttpUtils();
				}
			}

		}
		return okHttpUtils;
	}

	private static OkHttpClient okHttpClient = null;

	private synchronized static OkHttpClient getOkHttpClient() {
		if (okHttpClient == null) {
//			            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//			                @Override
//			                public void log(String message) {
//			                    Log.i("拦截器", message);
//			                }
//			            });
//			            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
			OkHttpClient.Builder build  = new OkHttpClient.Builder();//.addInterceptor(interceptor);
			build.followRedirects(false); //禁制OkHttp的重定向操作，我们自己处理重定向
			build.followSslRedirects(false);
					//请求超时时间
//			build.setFollowRedirects$okhttp(false);
			okHttpClient = build.connectTimeout(5, TimeUnit.SECONDS).build();
//			try {
//				okHttpClient.cache().delete();
//			}catch (Exception e)
//			{
//				e.printStackTrace();
//			}
		}
		return okHttpClient;
	}

	public void doGet(String url, Callback callback) {
		OkHttpClient okHttpClient = getOkHttpClient();
		Request request = new Request.Builder()
				.url(url)
				.build();
		okHttpClient.newCall(request).enqueue(callback);
	}
	public Response doGet(String urlStr) throws Exception{
		Log.debug(getClass(), "doGet urlStr = " + urlStr);
		HttpUrl url = HttpUrl.parse(urlStr);
		if (url == null) {
			Log.debug(getClass(), "doGet url = " + url);
			throw new IllegalArgumentException("Invalid URL");
		}
		OkHttpClient okHttpClient = getOkHttpClient();
		Request request = new Request.Builder()
				.url(url)
				.build();
		Response rsp = okHttpClient.newCall(request).execute();
		Log.debug(getClass(), "doGet code = " + rsp.code());
		return rsp;
	}
	//get方法
//	public void doGet(String url,String key, String accessToken,Callback callback) {
//		OkHttpClient okHttpClient = getOkHttpClient();
//		Request request = new Request.Builder()
//				.url(url)
//				.addHeader(key, "Bearer " + accessToken)
//				.build();
//		okHttpClient.newCall(request).enqueue(callback);
//	}

	public Response doGet(String urlStr,Map<String,String> headerMap) throws Exception {
		Log.debug(getClass(), "doGet urlStr = " + urlStr);
		OkHttpClient okHttpClient = getOkHttpClient();
		HttpUrl url = HttpUrl.parse(urlStr);
		if (url == null) {
			Log.debug(getClass(), "doGet url = " + url);
			throw new IllegalArgumentException("Invalid URL");
		}
		Request.Builder requestBuilder = new Request.Builder().url(url);
		for (String key : headerMap.keySet()) {
			String val = headerMap.get(key);
			System.out.println("Key = " + key + ", Value = " + val);
			requestBuilder.addHeader(key,val);
		}

		return okHttpClient.newCall(requestBuilder.build()).execute();
	}

	//doPost方法
	public Response doPutJson(String url, Map<String, String> params) throws Exception {

		OkHttpClient okHttpClient = getOkHttpClient();
//		try {
			MediaType JSON = MediaType.parse("application/json; charset=utf-8");
			JSONObject json = new JSONObject();
			FormBody.Builder builder = new FormBody.Builder();
			for (String key : params.keySet()) {
				builder.add(key, params.get(key));

				json.put(key, params.get(key));

			}
			Log.d(THIS_FILE, "doPutJson url = " + url + " json = " + json );
			RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
			Request request = new Request.Builder()
                    .url(url)
                    .put(requestBody)
                    .build();
			return okHttpClient.newCall(request).execute();

//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	public Response doPost(String url,  Map<String, String> params){
		Log.d(THIS_FILE, "doPost url = " + url + " params = " + params);
		FormBody.Builder formBuilder = new FormBody.Builder();
		for (String key : params.keySet()) {
			formBuilder.add(key, params.get(key));
		}

		// 构建请求体
		RequestBody requestBody = formBuilder.build();
		Request.Builder rb = new Request.Builder().url(url);
		rb.post(requestBody);
		rb.header("Content-Type","application/x-www-form-urlencoded");
		Request rq = rb.build();

		try {
			Response rsp = okHttpClient.newCall(rq).execute();
//			Log.d(THIS_FILE, "doPost rsp.code() = " + rsp.code());
			return rsp;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public Response doPost(String url, String cookie, Map<String, String> params){
		Log.d(THIS_FILE, "doPost url = " + url + " params = " + params);
		FormBody.Builder formBuilder = new FormBody.Builder();
		for (String key : params.keySet()) {
			formBuilder.add(key, params.get(key));
		}

		// 构建请求体
		RequestBody requestBody = formBuilder.build();
		Request.Builder rb = new Request.Builder().url(url);
//		Request build = new Request.Builder()
		if(cookie != null) {
			rb.addHeader("Cookie", cookie);
		}
		rb.post(requestBody);
		rb.header("Content-Type","application/x-www-form-urlencoded");
		Request rq = rb.build();

		try {
			Response rsp = okHttpClient.newCall(rq).execute();
//			Log.d(THIS_FILE, "doPost rsp.code() = " + rsp.code());
			return rsp;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public void doPostFile(String url,File file, long len, Callback callback,OnUploadListener listener,String infoBody) {
		Log.d(THIS_FILE, "doPostFile url = " + url + " file = " + file + " infoBody = " +  infoBody);
		
		MultipartBody.Builder builder = new MultipartBody.Builder();
		
//		builder.setType(MultipartBody.FORM);
		
		builder.addPart(RequestBody.create(MediaType.parse("application/vnd.3gpp.mcdata-info+xml"),infoBody));
//		builder.addFormDataPart("","",RequestBody.create(MediaType.parse("application/json"),json.toString()));
//		//第一个参数要与Servlet中的一致
		builder.addFormDataPart("file",file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));

		MultipartBody multipartBody = builder.build();
		String remoteFilePath = url + file.getName();
		Request request = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener,remoteFilePath,len)).build();
		Log.d(THIS_FILE, "doPostFile request = " + request);
		okHttpClient.newCall(request).enqueue(callback);

	}

	public void download(final String url, String jsonStr, Callback callback) {
		Log.d(THIS_FILE, "download url = " + url + " jsonStr = " + jsonStr );
//		MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//		RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsonStr));
		Request request = new Request.Builder()
                .url(url)
//                .put(requestBody)
                .build();
		//异步请求
		okHttpClient.newCall(request).enqueue(callback);
	}

	@Override
	public void onFailure(Call call, IOException e) {

	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {

	}

	public void doPostFile(String url,File file, Callback callback,OnUploadListener listener) {
		Log.d(THIS_FILE, "doPostFile url = " + url + " file = " + file );

//		try {
//			HttpClient client = new HttpClient();
//			PostMethod post = new PostMethod(url);
//			Part[] parts = { new FilePart("logFile", file), new StringPart("logType", "0") };
//			post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
//			client.executeMethod(post);
//		}
//		catch (Exception e)
//		{
//
//		}

		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

//		JSONObject json = new JSONObject();
//		try
//		{
//			json.put("logFile", file.getName());
//			json.put("logType", 0);
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}

//		builder.setType(MultipartBody.FORM);

		//builder.addFormDataPart("logType", "0");//.addPart(RequestBody.create(MediaType.parse("application/json"),json.toString()));
		//builder.addFormDataPart("logType",RequestBody.create(MediaType.parse("text/plain"),"0").toString());
		//builder.addFormDataPart("userphone", userPhone);
//		builder.addFormDataPart("logType","0");
		//builder.addFormDataPart("logType","0",RequestBody.create(MediaType.parse("text/plain"),"0"));
		builder.addFormDataPart("file",file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));
//		//第一个参数要与Servlet中的一致                            RequestBody.create(MEDIA_TYPE_MARKDOWN, file)
		//MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
		//builder.addFormDataPart("logFile",file.getName(), null);

		MultipartBody multipartBody = builder.build();
		String remoteFilePath = url + file.getName();
		Request request = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener,remoteFilePath,file.length())).build();
		Log.d(THIS_FILE, "doPostFile request = " + request);
		okHttpClient.newCall(request).enqueue(callback);
	}
}